package inet.db.tennis;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import inet.db.pool.*;
import inet.util.Logger;

public class TennisEventDAO {

	private Logger logger = null;
	private DBPoolX poolX = null;
	public TennisEventDAO(){
		logger = new Logger(this.getClass().getName());
		try{
			poolX = DBPoolX.getInstance(DBPoolXName.SERVICE_BONGDA);
		}catch(Exception exception){
			logger.log(exception.toString());
		}
	}
	
	/**
	 * function get a TennisEvent by id
	 * @param id
	 * @return TennisEvent object
	 */
    public TennisEvent getRow(BigDecimal id) {
        Connection conn = null;
        PreparedStatement preStmt = null;
        ResultSet rs = null;
        String strSQL = null;
        TennisEvent event = null;
        try {
            conn = poolX.getConnection();
            strSQL =
                "select ID, MATCH_ID, GAME_ID, SET_ID, SCORE1, SCORE2, SPECIAL_POINT, GEN_DATE, LAST_UPDATED " +
                "from TENNIS_EVENT where ID = ? ";
            preStmt = conn.prepareStatement(strSQL);
            preStmt.setBigDecimal(1, id);
            rs = preStmt.executeQuery();
            if (rs.next()) {
            	event = new TennisEvent();
            	event.setId(rs.getBigDecimal(1));
            	event.setMatchId(rs.getBigDecimal(2));
            	event.setGameId(rs.getBigDecimal(3));
            	event.setSetId(rs.getBigDecimal(4));
            	event.setScore1(rs.getString(5));
            	event.setScore2(rs.getString(6));
            	event.setSpecialPoint(rs.getInt(7));
            	event.setGenDate(rs.getTimestamp(8));
            	event.setLastUpdated(rs.getTimestamp(9));
            }
        }
        catch (SQLException e) {
            logger.error("getRow: Error executing SQL " + strSQL + ">>>" + e.toString());
        } finally {
            poolX.releaseConnection(conn, preStmt, rs);
        }
        return event;
    }
    
    /**
     * function last record of match in EVENT table
     * @param matchId
     * @return TennisEvent
     */
    public TennisEvent getLastRecordOfMatch(BigDecimal matchId, BigDecimal gameId) {
    	Connection conn = null;
    	PreparedStatement preStmt = null;
    	ResultSet rs = null;
    	String strSQL = null;
    	TennisEvent event = null;
    	try {
    		conn = poolX.getConnection();
    		strSQL =
    			"select ID, MATCH_ID, GAME_ID, SET_ID, SCORE1, SCORE2, SPECIAL_POINT, GEN_DATE, LAST_UPDATED, SERVE " +
    			"from TENNIS_EVENT where MATCH_ID = ? and GAME_ID = ? order by ID desc, GEN_DATE desc ";
    		preStmt = conn.prepareStatement(strSQL);
    		preStmt.setBigDecimal(1, matchId);
    		preStmt.setBigDecimal(2, gameId);
    		rs = preStmt.executeQuery();
    		if (rs.next()) {
    			event = new TennisEvent();
    			event.setId(rs.getBigDecimal(1));
    			event.setMatchId(rs.getBigDecimal(2));
    			event.setGameId(rs.getBigDecimal(3));
    			event.setSetId(rs.getBigDecimal(4));
    			event.setScore1(rs.getString(5));
    			event.setScore2(rs.getString(6));
    			event.setSpecialPoint(rs.getInt(7));
    			event.setGenDate(rs.getTimestamp(8));
    			event.setLastUpdated(rs.getTimestamp(9));
    			event.setServe(rs.getInt(10));
    		}
    	}
    	catch (SQLException e) {
    		logger.error("getLastRecordOfMatch: Error executing SQL " + strSQL + ">>>" + e.toString());
    	} finally {
    		poolX.releaseConnection(conn, preStmt, rs);
    	}
    	return event;
    }
    
    /**
     * get last event of match
     * @param matchId
     * @return TennisEvent
     */
    public TennisEvent getLastRecordOfMatch(BigDecimal matchId) {
    	Connection conn = null;
    	PreparedStatement preStmt = null;
    	ResultSet rs = null;
    	String strSQL = null;
    	TennisEvent event = null;
    	try {
    		conn = poolX.getConnection();
    		strSQL =
    			"select ID, MATCH_ID, GAME_ID, SET_ID, SCORE1, SCORE2, SPECIAL_POINT, GEN_DATE, LAST_UPDATED, SERVE " +
    			"from TENNIS_EVENT where MATCH_ID = ? order by ID desc, GEN_DATE desc ";
    		preStmt = conn.prepareStatement(strSQL);
    		preStmt.setBigDecimal(1, matchId);
    		rs = preStmt.executeQuery();
    		if (rs.next()) {
    			event = new TennisEvent();
    			event.setId(rs.getBigDecimal(1));
    			event.setMatchId(rs.getBigDecimal(2));
    			event.setGameId(rs.getBigDecimal(3));
    			event.setSetId(rs.getBigDecimal(4));
    			event.setScore1(rs.getString(5));
    			event.setScore2(rs.getString(6));
    			event.setSpecialPoint(rs.getInt(7));
    			event.setGenDate(rs.getTimestamp(8));
    			event.setLastUpdated(rs.getTimestamp(9));
    			event.setServe(rs.getInt(10));
    		}
    	}
    	catch (SQLException e) {
    		logger.error("getLastRecordOfMatch: Error executing SQL " + strSQL + ">>>" + e.toString());
    	} finally {
    		poolX.releaseConnection(conn, preStmt, rs);
    	}
    	return event;
    }
    
    /**
     * function get max id of match
     * @param matchId
     * @return BigDecimal maxId
     */
    public BigDecimal getMaxIdOfMatch(BigDecimal matchId, BigDecimal gameId) {
    	if(matchId == null) return null;
    	Connection conn = null;
    	PreparedStatement preStmt = null;
    	ResultSet rs = null;
    	String strSQL = null;
    	BigDecimal maxId = BigDecimal.ZERO;
    	try {
    		conn = poolX.getConnection();
    		strSQL =
    			"select max(ID) " +
    			"from TENNIS_EVENT where MATCH_ID = ? and GAME_ID = ? ";
    		preStmt = conn.prepareStatement(strSQL);
    		preStmt.setBigDecimal(1, matchId);
    		preStmt.setBigDecimal(2, gameId);
    		rs = preStmt.executeQuery();
    		if (rs.next()) {
    			maxId = rs.getBigDecimal(1);
    		}
    	}
    	catch (SQLException e) {
    		logger.error("getMaxIdOfMatch: Error executing SQL " + strSQL + ">>>" + e.toString());
    	} finally {
    		poolX.releaseConnection(conn, preStmt, rs);
    	}
    	return maxId;
    }
    
    /**
     * fucntion get all TennisEvent
     * @return Vector 
     * TennisEvent (Full)
     */
    public Vector findAll() {
    	Connection conn = null;
    	PreparedStatement preStmt = null;
    	ResultSet rs = null;
    	String strSQL = null;
    	TennisEvent event = null;
    	Vector vEvent = null;
    	
    	try {
    		conn = poolX.getConnection();
    		strSQL =
    			"select ID, MATCH_ID, SCORE1, SCORE2, SET_ID, SERVE, TYPE, GEN_DATE, LAST_UPDATED " +
                "from TENNIS_SET order by ID desc, GEN_DATE desc ";
    		preStmt = conn.prepareStatement(strSQL);
    		rs = preStmt.executeQuery();
    		vEvent = new Vector();
    		while (rs.next()) {
    			event = new TennisEvent();
            	event.setId(rs.getBigDecimal(1));
            	event.setMatchId(rs.getBigDecimal(2));
            	event.setGameId(rs.getBigDecimal(3));
            	event.setSetId(rs.getBigDecimal(4));
            	event.setScore1(rs.getString(5));
            	event.setScore2(rs.getString(6));
            	event.setSpecialPoint(rs.getInt(7));
            	event.setGenDate(rs.getTimestamp(8));
            	event.setLastUpdated(rs.getTimestamp(9));
            	
            	vEvent.addElement(event);
    		}
    	}
    	catch (SQLException e) {
    		logger.error("findAll: Error executing SQL " + strSQL + ">>>" + e.toString());
    	} finally {
    		poolX.releaseConnection(conn, preStmt, rs);
    	}
    	return vEvent;
    }
	
    /**
     * function insert full data to Tennis Event
     * @param matchId
     * @param setId
     * @param gameId
     * @param score1
     * @param score2
     * @param specialPoint
     * @return true if insert success else return false.
     */
    @Deprecated
	public boolean insertRow(BigDecimal matchId, BigDecimal setId, BigDecimal gameId, String score1, String score2, int specialPoint){
		Connection conn = null;
        PreparedStatement preStmt = null;
        boolean result = false;
        String strSQL = null;
        try {
            conn = poolX.getConnection();

        	strSQL =" insert into TENNIS_EVENT( ID, MATCH_ID, SET_ID, GAME_ID, SCORE1, SCORE2, SPECIAL_POINT) " +
    				" values(TENNIS_EVENT_SEQ.nextval, ?, ?, ?, ?, ?, ?) ";
	        preStmt = conn.prepareStatement(strSQL);
	        preStmt.setBigDecimal(1, matchId);
	        preStmt.setBigDecimal(2, setId);
	        preStmt.setBigDecimal(3, gameId);
	        preStmt.setString(4, score1);
	        preStmt.setString(5, score2);
	        preStmt.setInt(6, specialPoint);
	        
	        if (preStmt.executeUpdate()>=1) {
	        	result = true;
	        }
        } catch (Exception ex) {
        	logger.error("insertRow: Error executing SQL " + strSQL + ">>>" + ex.toString());
        } finally {
        	poolX.releaseConnection(conn, preStmt);
       }
       return result;
	}
	
	/**
	 * function insert full data with serve
	 * @param matchId
	 * @param setId
	 * @param gameId
	 * @param score1
	 * @param score2
	 * @param specialPoint
	 * @param serve
	 * @return true if insert success else return false.
	 */
	public boolean insertRow(BigDecimal matchId, BigDecimal setId, BigDecimal gameId, String score1, String score2, int specialPoint, int serve){
		Connection conn = null;
		PreparedStatement preStmt = null;
		boolean result = false;
		String strSQL = null;
		try {
			conn = poolX.getConnection();
			
			strSQL =" insert into TENNIS_EVENT( ID, MATCH_ID, SET_ID, GAME_ID, SCORE1, SCORE2, SPECIAL_POINT, SERVE) " +
			" values(TENNIS_EVENT_SEQ.nextval, ?, ?, ?, ?, ?, ?, ?) ";
			preStmt = conn.prepareStatement(strSQL);
			preStmt.setBigDecimal(1, matchId);
			preStmt.setBigDecimal(2, setId);
			preStmt.setBigDecimal(3, gameId);
			preStmt.setString(4, score1);
			preStmt.setString(5, score2);
			preStmt.setInt(6, specialPoint);
			preStmt.setInt(7, serve);
			
			if (preStmt.executeUpdate()>=1) {
				result = true;
			}
		} catch (Exception ex) {
			logger.error("insertRow: Error executing SQL " + strSQL + ">>>" + ex.toString());
		} finally {
			poolX.releaseConnection(conn, preStmt);
		}
		return result;
	}
	
	/**
	 * function update Score and special point of tennis Event
	 * @param id
	 * @param score1
	 * @param score2
	 * @param specialPoint
	 * @return true if update success else return false.
	 */
	public boolean updateScore(BigDecimal id, String score1, String score2, int specialPoint){
		Connection conn = null;
        PreparedStatement preStmt = null;
        boolean result = false;
        String strSQL = null;
        try {
        	conn = poolX.getConnection();
        	strSQL =" update TENNIS_GAME set SCORE1 = ?, SCORE2 = ?, SPECIAL_POINT = ?, LAST_UPDATED = sysdate " +
        			" where ID = ?";
        	preStmt = conn.prepareStatement(strSQL);
        	preStmt.setString(1, score1);
        	preStmt.setString(2, score2);
        	preStmt.setInt(3, specialPoint);
        	preStmt.setBigDecimal(4, id);
        	
        	if(preStmt.executeUpdate() > 0){
        		result = true;
        	}
        } catch (Exception ex) {
        	logger.error("updateScore: Error executing SQL " + strSQL + ">>>" + ex.toString());
        } finally {
        	poolX.releaseConnection(conn, preStmt);
       }
        return result;
	}
	
	/**
	 * function delete a Tennis EVENT
	 * @param id
	 * @return true if update success else return false.
	 */
	public boolean deleteRow(BigDecimal id){
		Connection conn = null;
		PreparedStatement preStmt = null;
		boolean result = false;
		String strSQL = null;
		try {
			conn = poolX.getConnection();
			strSQL =" delete from TENNIS_EVENT where ID = ? ";
			preStmt = conn.prepareStatement(strSQL);
			preStmt.setBigDecimal(1, id);
			if(preStmt.executeUpdate() > 0){
				result = true;
			}
		} catch (Exception ex) {
			logger.error("deleteRow: Error executing SQL " + strSQL + ">>>" + ex.toString());
		} finally {
			poolX.releaseConnection(conn, preStmt);
		}
		return result;
	}
}
